/** @type {import('next').NextConfig} */
// Next.js配置文件需要使用CommonJS模块格式
// 导入必要模块
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

// 获取MQTT配置环境变量
const getMqttEnvVars = () => {
  const mqttEnvVars = {};
  
  // MQTT相关环境变量（带NEXT_PUBLIC_前缀）
  const mqttVarKeys = [
    'NEXT_PUBLIC_MQTT_HOST',
    'NEXT_PUBLIC_MQTT_PORT', 
    'NEXT_PUBLIC_MQTT_USERNAME',
    'NEXT_PUBLIC_MQTT_PASSWORD',
    'NEXT_PUBLIC_MQTT_PROTOCOL'
  ];
  
  // 将存在的环境变量添加到配置中
  mqttVarKeys.forEach(key => {
    if (process.env[key]) {
      mqttEnvVars[key] = process.env[key];
    }
  });
  
  return mqttEnvVars;
};

const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
  // 为Docker部署添加独立输出配置
  output: 'standalone',
  // 暂时禁用next.js的CSP配置
  async headers() {
    return [];
  },
  // 将MQTT环境变量传递给前端
  env: {
    ...getMqttEnvVars()
  },
  webpack: (config, { isServer }) => {
    if (!isServer) {
      // 将默认环境标记为 browser
      config.resolve.fallback = {
        ...config.resolve.fallback,
        fs: false,
        path: false,
      };
      
      // 添加 Cesium 资源复制配置
      config.plugins.push(
        new CopyWebpackPlugin({
          patterns: [
            {
              from: path.join(
                __dirname,
                'node_modules/cesium/Build/Cesium/Workers'
              ),
              to: path.join(__dirname, 'public/cesium/Workers'),
            },
            {
              from: path.join(
                __dirname,
                'node_modules/cesium/Build/Cesium/ThirdParty'
              ),
              to: path.join(__dirname, 'public/cesium/ThirdParty'),
            },
            {
              from: path.join(
                __dirname,
                'node_modules/cesium/Build/Cesium/Assets'
              ),
              to: path.join(__dirname, 'public/cesium/Assets'),
            },
            {
              from: path.join(
                __dirname,
                'node_modules/cesium/Build/Cesium/Widgets'
              ),
              to: path.join(__dirname, 'public/cesium/Widgets'),
            },
            {
              from: path.join(
                __dirname,
                'node_modules/cesium/Build/Cesium/Cesium.js'
              ),
              to: path.join(__dirname, 'public/cesium/Cesium.js'),
            },
          ],
        })
      );
      
      // 将Cesium作为外部库处理，而不是试图打包它
      config.externals = {
        ...config.externals,
        cesium: 'Cesium'
      };
    }

    return config;
  },
  // 禁用默认的静态优化，以确保正确处理动态导入
  // optimizeFonts: false, // 移除此行，不支持的选项
  // 配置输出目录和缓存
  distDir: '.next',
  generateBuildId: () => 'build',
}

module.exports = nextConfig;